package org.xx.armory.ofs;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Pattern;

public final class FileRefUtils {
    private static final String HASH_ALGORITHM = "SHA-1";
    private static final Pattern HASH_NORM_FILTER = Pattern.compile("[/*%=+-]");

    private FileRefUtils() {
        throw new UnsupportedOperationException();
    }

    public static String hashFile(
            long id,
            String name
    ) {
        final var a = Objects.hash(id, name);
        final var b = new byte[]{(byte) (a & 255), (byte) (a >> 8 & 255), (byte) (a >> 16 & 255), (byte) (a >> 24 & 255)};

        final byte[] c;
        try {
            c = MessageDigest.getInstance(HASH_ALGORITHM).digest(b);
        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Cannot create MessageDigest", ex);
        }

        return HASH_NORM_FILTER.matcher(Base64.getEncoder().encodeToString(c).substring(2, 8)).replaceAll("_");
    }

    public static UUID createUuid() {
        return UUID.randomUUID();
    }
}

